<script setup>
import { computed, inject, onMounted, reactive, ref } from 'vue'
import {IconArrowLeft} from '../icon/index.js'
import { DlMessageBox } from '../util/messagebox.js';
import { IconHomeAlt, IconCart, IconUser, IconTopCircle, IconTriangleDown, IconTriangleUp } from '../icon/index.js'
import DlLoading from '../components/DlLoading.vue'
import ProductBox from '../components/ProductBox.vue'
import SearchBox from '../components/SearchBox.vue'

//引入 api
import { searchProductFun } from '../api/product.js'
import { addToCartFun } from '../api/cart.js'

//获取搜索关键字
const searchKey = inject('searchKey');

// 1 降序, -1 升序
const sortObj = reactive({
    all: {key:'all', selected: true, sort: 1}, //综合
    sell: {key:'sell',selected: false, sort: 1}, // 销量
    price: {key:'price',selected: false, sort: 1}, //价格
    time: {key:'time',selected: false, sort: 1} // 上架时间
});
let selectSort = sortObj.all;
const productArr = ref([]);//数据
const currentPageNum = ref(1);
const pageSize = 5;
const pages = ref(0);//总页数
const loading = ref(false);//加载中
const noMoreData = ref(false);//是否已没有更多数据了
//加载数据
function doLoadData() {
    noMoreData.value = false;
    loading.value = true;
    //根据条件查询商品
    //请求参数
    let params = {
        pageNum: currentPageNum.value,
        pageSize: pageSize,
        keyWord: searchKey.value, // 搜索关键字
        sortKey: selectSort.key,// 排序依据
        sort: selectSort.sort, //1 降序, -1 升序
    };
    console.log('params:', params);
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
    
            let key = productArr.value.length + 1;
            for(let i=0; i<5; i++) {
                dataArr.push({id: i+key, title: '测试测试测试测试-'+(i+key), image: './product.jpg', price: 99.99, type:['红色','绿色','蓝色'], status:1});
            }
    
            dataArr.forEach(p => productArr.value.push(p));
            pages.value = 5;
            loading.value = false;
            noMoreData.value = currentPageNum.value >= pages.value;
        }, 1000);
    } else {
        //请求api
        searchProductFun(params.pageNum, params.pageSize, params.keyWord, params.sortKey, params.sort)
        .then((result)=>{
            console.log('searchProductFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                let data = result.data;
                data.list.forEach(p => productArr.value.push(p));
                pages.value = data.pages;
                noMoreData.value = currentPageNum.value >= pages.value;
            } else {
                DlMessageBox.error(result.msg);
            }
            loading.value = false;
        });
    }

}

//搜索
function doSearch(key) {
    console.log('doSearch:', key);
    if(!key || !key.trim()) {
        DlMessageBox.warning('请输入搜索内容');
        return;
    }
    if(loading.value) {
        DlMessageBox.warning('处理中！\n请稍候再试！');
        return;
    }
    searchKey.value = key;

    //重新搜索
    currentPageNum.value = 1;
    productArr.value = [];
    pages.value = 0;
    doLoadData();
}

//排序
function doChangeSort(selectObj) {
    //console.log('select:', selectObj);
    if(loading.value) {
        DlMessageBox.warning('处理中！\n请稍候再试！');
        return;
    }
    let selected = selectObj.selected;
    // 移除选中
    for(let key in sortObj) {
        sortObj[key].selected = false;
    }
    //切换排序规则
    if(selected) {
        selectObj.sort = -1*selectObj.sort;
    }
    selectObj.selected = true;
    selectSort = selectObj;

    //重新搜索
    currentPageNum.value = 1;
    productArr.value = [];
    pages.value = 0;
    doLoadData();
}


//底部主菜单
const homeMenuBar = inject('homeMenuBar');
const viewRef = ref(null);
const viewHeight = computed(()=>{//计算展示区域高度
    let vh = 770;
    if(viewRef.value) {
        let p = viewRef.value.parentElement;
        vh = p.offsetHeight;
    }
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        vh -= h;
    }
    return vh;
});

//滚动事件
function doChangeScroll(e) {
    // console.log('doChangeScroll:', e);
    let t = e.target;
    //回到顶部按钮处理, 显示与隐藏
    showTopBtn.value = t.scrollTop > showHideTop;

    let offsetNum = 10;//误差值
    let height = t.scrollHeight - t.offsetHeight - t.scrollTop - offsetNum;
    // 到底加载更多
    if(height <= 0) {
        console.log('滚动到底部了...');
        //如果还有数据,则加载;如果正在加载中,则不再执行
        if(!loading.value && currentPageNum.value < pages.value) {
            currentPageNum.value++;
            doLoadData();
        }
    }
}
const showTopBtn = ref(false);
const showHideTop = 300;//隐藏和显示的scrollTop
const showAllRightMenu = ref(true);//显示和隐藏右侧所有菜单
const topBtnStyle = computed(()=>{
    let bottom = 100;
    let right = -1.8;
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        bottom+=h;
    }
    if(showTopBtn.value) {
        right = 0.6;
    }
    let obj = {bottom: bottom+'px', right: right+'rem'};
    return obj;
});
//回到顶部
function doGoTop() {
    if(viewRef.value) {
        viewRef.value.scrollTo({top: 0, behavior: 'smooth'});
    }
}
//主菜单核心
const menuCore = inject('menuCore');
//去购物车
function doGoCartView() {
    menuCore.push('/cart');
}
//去home
function doGoHomeView() {
    menuCore.push('/home');
}
//去我的
function doGoUserView() {
    menuCore.push('/user');
}
//后退
function doGoBack() {
    menuCore.back();
}

// 去详情
function goDetail(product) {
    localStorage.setItem('detailProductId', product.id);
    menuCore.push('/detail');
}

//购物车
const cart = inject('cart');
// 加入购物车
function doAddCart(product) {
    //加入购物车
    if (window && window.enableDl) {
        //模拟
        if(cart[product.id]){
            cart[product.id].num++;
        } else {
            cart[product.id] = {
                productId: product.id, image: product.image, title: product.title, price: product.price, type: product.type, num: 1, checked: false,
                endTime: product.endTime,
                miaoShaId: product.miaoShaId,
            };
        }
        //成功后执行以下操作
        DlMessageBox.success('加入成功');
        //console.log('cart:', cart);
    } else {
        addToCartFun(product.id, product.miaoShaId).then((result)=>{
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}

onMounted(()=> {
    doLoadData();
});

</script>
<template>
    <div class="view-dl" ref="viewRef" :style="'height:'+viewHeight+'px'" @scroll="doChangeScroll">
        <div class="head-dl">
            <div class="top-title-dl">
                <div class="back-icon-dl" @click="doGoBack">
                    <IconArrowLeft />
                </div>
                <div>搜索</div>
            </div>
            <SearchBox @search="doSearch" :key-word="searchKey" />
        </div>

        <div class="content-dl">
            <!-- 排序 -->
            <div class="sort-list-dl">
                <div class="sort-item" @click="doChangeSort(sortObj.all)" :class="(sortObj.all.selected?'sort-active-dl':'')">
                    <span>综合</span>
                    <IconTriangleDown v-if="sortObj.all.sort == 1" class="icon-dl" />
                    <IconTriangleUp v-else class="icon-dl" />
                </div>
                <div class="sort-item" @click="doChangeSort(sortObj.sell)" :class="(sortObj.sell.selected?'sort-active-dl':'')">
                    <span>销量</span>
                    <IconTriangleDown v-if="sortObj.sell.sort == 1" class="icon-dl" />
                    <IconTriangleUp v-else class="icon-dl" />
                </div>
                <div class="sort-item" @click="doChangeSort(sortObj.price)" :class="(sortObj.price.selected?'sort-active-dl':'')">
                    <span>价格</span>
                    <IconTriangleDown v-if="sortObj.price.sort == 1" class="icon-dl" />
                    <IconTriangleUp v-else class="icon-dl" />
                </div>
                <div class="sort-item" @click="doChangeSort(sortObj.time)" :class="(sortObj.time.selected?'sort-active-dl':'')">
                    <span>上架时间</span>
                    <IconTriangleDown v-if="sortObj.time.sort == 1" class="icon-dl" />
                    <IconTriangleUp v-else class="icon-dl" />
                </div>
            </div>

            <!-- 数据 -->
            <div class="data-list-dl">
                <template v-for="p in productArr" :key="p.id">
                    <ProductBox :product="p" @go-detail="goDetail" @add-cart="doAddCart" class="pfs-dl" />
                </template>
            </div>

            <div class="load-box-dl" >
                <!-- 加载中动画... -->
                <DlLoading style="font-size: 1rem" v-show="loading" />
                <div class="no-more-data-dl" v-show="!loading && noMoreData">暂无更多商品</div>
            </div>
        </div>        

        

        <div class="top-btn-dl" :style="topBtnStyle">
            <div class="menu-list-dl" :style="'height:'+ (showAllRightMenu?'5.6':'0') +'rem;'">
                <IconHomeAlt class="icon-dl" @click="doGoHomeView" />
                <IconCart class="icon-dl" @click="doGoCartView" />
                <IconUser class="icon-dl" @click="doGoUserView" />
                <IconTopCircle class="icon-dl" @click="doGoTop" />
            </div>
            
            <IconTriangleDown v-if="showAllRightMenu" class="icon-dl" @click="showAllRightMenu=false" />
            <IconTriangleUp v-else class="icon-dl" @click="showAllRightMenu=true" />
        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    overflow: hidden auto;
}

.head-dl {
    background-color: #fff;
    padding: 0.14rem 0.38rem;
    font-size: 1rem;
    color: #333;
}
.top-title-dl {
    font-weight: bold;
    font-size: 0.6rem;
    text-align: center;
    position: relative;
}
.back-icon-dl {
    position: absolute;
    width: 0.8rem;
    height: 0.8rem;
    cursor: pointer;
    top: 50%;
    left: 0;
    transform: translate(0, -50%);
}

.content-dl {
    margin-bottom: 0.4rem;
}
.sort-list-dl {
    padding: 0.2rem 0.2rem;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    margin: 0.1rem 0;
}
.sort-item {
    flex-shrink: 0;
    cursor: pointer;
    border: 1px solid #000;
    border-radius: 1rem;
    padding: 0 0.1rem;
    color: #333;
}
.sort-item .icon-dl {
    width: 0.5rem;
    height: 0.5rem;
    vertical-align: top;
}
.sort-active-dl {
    color: #900;
}

.data-list-dl {
    display: flex;
    flex-wrap: wrap;
}

.pfs-dl {
    font-size: 2.28rem;
    margin-left: 0.293rem;
    background-color: #fff;
    color: #333;
}

.load-box-dl {
    text-align: center;
    color: #aaa;
    margin-top: 0.5rem;
    padding: 0.2rem;
}
.load-box-dl .no-more-data-dl {
    font-size: 0.4rem;
    border-top: 1px solid #ccc;
    padding-top: 0.2rem;
}

.top-btn-dl {
    position: fixed;
    transition: all 0.2s linear;
    width: 1.4rem;
    font-size: 0;
}
.top-btn-dl .icon-dl {
    width: 1.4rem;
    height: 1.4rem;
    color: #fff;
    background-color: #999c;
    border-radius: 50%;
    cursor: pointer;
}
.menu-list-dl {
    transition: all 0.4s linear;
    overflow: hidden;
}
</style>